--[[
     Created by IntelliJ IDEA.
     User: 毛凯
     Date: 2018/7/30
     Time: 9:38
     参数：ARGV[1]:活动id
     参数：ARGV[2]:标记  1，随机红包，2点赞红包，3被点赞红包
     参数：ARGV[3]:红包金额
     返回：返回数组：
           1表示成功 0失败
--]]

--记录活动红包以及人数key
local ACTINFOKEY = 'act_'..ARGV[1]
-- 记录初始化信息key
local ACTINITKEY = 'actInit_'..ARGV[1]

--标记
local flag = tonumber(ARGV[2]) or 0

--剩余总奖金
local rewardRemaining = 0
--已发奖金人数
local rewardUserCnt = 0
--活动id
local act = tonumber(ARGV[1]) or 0
local redPackage = tonumber(ARGV[3]) or 0

--当红包为0是直接返回
if(redPackage == 0)
then
    return 0
end
--flag为1是获取随机红包值
if(flag == 1)
then
     rewardRemaining = tonumber(redis.call('hget',ACTINFOKEY,'randomRemaining')) or 0
     rewardUserCnt = tonumber(redis.call('hget',ACTINFOKEY,'randomParticipants')) or 0
end
--flag为2是获取随点赞红包
if(flag == 2)
then
    rewardRemaining = tonumber(redis.call('hget',ACTINFOKEY,'likeRemaining')) or 0
    rewardUserCnt = tonumber(redis.call('hget',ACTINFOKEY,'likeParticipants')) or 0
end
--flag为3是获取被点赞红包
if(flag == 3)
then
    rewardRemaining = tonumber(redis.call('hget',ACTINFOKEY,'praisedRemaining')) or 0
    rewardUserCnt = tonumber(redis.call('hget',ACTINFOKEY,'praisedParticipants')) or 0
end
--当红包金额大于余额
if(redPackage > rewardRemaining)
then
    redPackage = rewardRemaining
end

--最新余额
local newRewardRemaining = rewardRemaining-redPackage
--最新人数
local newRewardUserCnt = rewardUserCnt + 1

--根据标记分别更新对应字段
if(flag == 1)
then
    redis.call('hset',ACTINFOKEY,'randomRemaining',newRewardRemaining)
    redis.call('hset',ACTINFOKEY,'randomParticipants',newRewardUserCnt)
end

if(flag == 2)
then
    redis.call('hset',ACTINFOKEY,'likeRemaining',newRewardRemaining)
    redis.call('hset',ACTINFOKEY,'likeParticipants',newRewardUserCnt)
end

if(flag == 3)
then
    redis.call('hset',ACTINFOKEY,'praisedRemaining',newRewardRemaining)
    redis.call('hset',ACTINFOKEY,'praisedParticipants',newRewardUserCnt)
end

return redPackage